package cn.qianxun.meta.common.core.httpclient;

import cn.hutool.core.text.UnicodeUtil;
import cn.qianxun.meta.common.core.constant.Constants;
import lombok.SneakyThrows;

import java.util.HashMap;

/**
 * @author fuzhilin
 */
public class RequestUtil {


    /**
     * 第三方接口调用方式
     *
     * @param url       请求地址
     * @param param     请求参数
     * @param way       请求方式 get post
     * @param headerMap 请求头 headerMap
     * @return String
     */
    @SneakyThrows
    public static String requestApi(String url, HashMap<String, Object> param, String way, HashMap<String, String> headerMap) {
        HttpClientResult httpClientResult = null;

        try {
            if (Constants.GET.equals(way)) {
                httpClientResult = HttpClientUtils.doGet(url, headerMap, param, null, null);
            } else if (Constants.POST.equals(way)) {
                httpClientResult = HttpClientUtils.doPost(url, headerMap, param, null, null);
            } else if (Constants.POST_FORM.equals(way)) {
                httpClientResult = HttpClientUtils.doPostForm(url, headerMap, param, null, null);
            } else if (Constants.BODY.equals(way)) {
                httpClientResult = HttpClientUtils.doPostJson(url, headerMap, param, null, null);
            } else if (Constants.DELETE.equals(way)) {
                httpClientResult = HttpClientUtils.doDeleteJson(url, headerMap, param);
            } else if (Constants.PUT.equals(way)) {
                httpClientResult = HttpClientUtils.doPut(url, headerMap, param, null, null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //对返回数据进行解析
        assert httpClientResult != null;
        return UnicodeUtil.toString(httpClientResult.getContent());
    }


}
